package cn.bs.seckill.validator;

import cn.bs.seckill.utils.ValidatorUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MobileValidator implements ConstraintValidator<IsMobile, String> {


    private boolean required = false;

    //初始化,因为是手机号,所以我们就判断是否为必填
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        //调用此方法,把required赋值为真
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        //如果是必填
        if (required) {
            //判断手机号格式是否正确
            return ValidatorUtil.isMobile(s);
        }
        //如果是非必填
        else {
            //返回为真
            if (StringUtils.isEmpty(s)) {
                return true;
            } else {
                //判断格式是否正确
                return ValidatorUtil.isMobile(s);
            }
        }

    }
}
